Page({
  data: {
        //用户全局信息
        userInfo: null,
        checkDish:[],
        totalPrice: 0,
        selectedDishes:[],
        allDish: [],
        dish:[],
        number: 1,
        address:"",
        userName:"",
        userPhoneNumber:"",
        zone:""
  },
  onLoad(options) {
    const checkDishJson = options.checkDish;
    // 将JSON字符串解码回数组
    const checkDishArray = JSON.parse(decodeURIComponent(checkDishJson));
    
    this.setData({
      selectedDishes: checkDishArray
    });
    this.setData({
      userInfo: app.globalData.userInfo
    })
    console.log(this.data.selectedDishes)
    this.init();
  },
  onShow: function() {
    // 当页面从后台进入前台时，获取全局的 selectedAddress 并渲染
    const selectedAddress = getApp().globalData.selectedAddress;
    console.log(selectedAddress)
    if (selectedAddress) {
      this.setData({
        zone: selectedAddress.zone,
        address: selectedAddress.address,
        userName: selectedAddress.name,
        userPhoneNumber:selectedAddress.phone
      });
    }
  },
  async init() {
    let openId = this.data.userInfo._openid;
    await this.getShopByUserId(openId);
    this.getDish();
    this.totalPriceFunction();
    console.log(this.data.totalPrice)
  },
  async getDish()
  {
    console.log(this.data.allDish)
    const myDish = this.data.allDish.filter(item => {
      // 直接返回条件表达式的结果
      if(item==null)console.log('哈哈哈')
      return this.data.selectedDishes.includes(item._id); // 确保属性名匹配
    });
    this.setData({
      dish: myDish // 更新页面的 dish 数据
    });
    console.log(this.data.dish)
  },
  async getShopByUserId(id) {
    try {
      const res = await wx.cloud.callFunction({
        name: 'getShopByUserId',
        data: {
          openId: id
        }
      });
      if (res.result.code === 0) {
        await this.setData({
          allDish: res.result.data.data
        });
      } else {
        console.error('获取食物失败:', res.result.msg);
      }
    } catch (err) {
      console.error('调用云函数时发生错误:', err);
    }
  },
  changeNumber(evt) {
    const index = evt.currentTarget.dataset.index;
  // 获取新的数值
  const number = evt.detail;
  console.log(number);
  // 更新对应菜品的数量
  const dish = this.data.dish;
  dish[index].number = number;
  // 更新页面数据
  this.setData({
    dish: dish
  });
  console.log(this.data.dish);

  this.updateShop(dish[index]._id,number);
  // 重新计算总价
  this.totalPriceFunction();
  },
	async totalPriceFunction() {
		let total = 0;
		this.data.dish.forEach((item) => {
      total = total + item.foodPrice * 0.01 * item.number;
    });
    let mytotalPrice=Number(total.toFixed(2));
    this.setData({
      totalPrice:mytotalPrice
    })
	},
  async updateShop(id,number){
    console.log(id);
    console.log(number);
    try {
      const res = await wx.cloud.callFunction({
        name: 'updateShop',
        data: {
          id:id,
          number:Number(number)  
        }
      });
      if (res.result.status === 0) {
        console.log(this.data.dish); // 打印更新后的食物列表数据
      } else {
        console.error('更新失败:', res.result.msg);
      }
    } catch (err) {
      console.error('调用云函数时发生错误:', err);
    }
  },
  toAddress(){
    wx.navigateTo({
      url: '/pages/address/address',
    })
  },
  checkToBuy(){
    wx.requestPayment({
      // 时间戳
      timeStamp: '',
      // 随机字符串
      nonceStr: '',
      // 统一下单接口返回的 prepay_id 参数值
      package: '',
      // 签名类型
      signType: '',
      // 签名
      paySign: '',
      // 调用成功回调
      success () {},
      // 失败回调
      fail () {},
      // 接口调用结束回调
      complete () {}
    })
  }
})
const app=getApp()